# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import argparse
import os
import shutil
import time
from config import SAVE_DIR, BLACKLIST_DEFAULT, GREYLIST_DEFAULT
import config
from data_summary import DataAnalys, WriteOkLibInfo, WriteOverview
import openpyxl
from find_build_script import BuildScripts

# Press the green button in the gutter to run the script.
from ndk_analyzer import relevant_func_analyzer
from black_list import BlackList

def _get_sub_libs(file_path):
    """
        description: get first sub libs path list in target dir
    """
    ret = []
    for f in os.listdir(file_path):
        tmpPath = os.path.join(file_path, f)
        if os.path.isdir(tmpPath):
            ret.append(f)
    return ret

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--folder', help='specify the root dir saved third_party libs, must supplied', type=str)
    parser.add_argument('-d', '--destination', help='specify the output directory, default in out directory', type=str)
    parser.add_argument('-b', '--black', help='specify the black list root, must supplied', type=str)
    # parser.add_argument('-g', '--grey', help='specify the grey list root, must supplied', type=str)

    args = parser.parse_args()
    if args.folder:
        software_root = os.path.abspath(args.folder)
        root_name = os.path.split(software_root)[-1]
        print(root_name)
    else:
        print('input source root path could not be empty')
        quit(-1)
    if args.black:
        blackList_path = args.black
    else:
        blackList_path = BLACKLIST_DEFAULT
    if args.destination:
        SAVE_DIR = args.destination

    if os.path.exists(SAVE_DIR):
        shutil.rmtree(SAVE_DIR)
    os.mkdir(SAVE_DIR)

    config.THIRD_LIB_ROOT = software_root
    # print(config.THIRD_LIB_ROOT)
    black_list = BlackList(blackList_path)
    sub_libs = _get_sub_libs(software_root)
    for sub_lib in sub_libs:
        lib_path = os.path.join(software_root, sub_lib)
        time_start = time.perf_counter()
        relevant_func_analyzer(lib_path, black_list, sub_lib, SAVE_DIR, root_name)
        time_end = time.perf_counter()
        print(f'Process {sub_lib} Takes Time {time_end - time_start} seconds')
        print('finished')

    # 风险数据统计
    excelFile = SAVE_DIR + root_name + '_risk_assessment.xlsx'
    wb = openpyxl.load_workbook(excelFile)
    riskLibs = DataAnalys(wb, root_name)
    # 挑出无风险库
    okLibs = [lib for lib in sub_libs if lib not in riskLibs]
    # print("okLibs: ", okLibs)
    # print(len(okLibs))
    # 识别出三方库的构建方式
    buildScript = {}
    for lib in sub_libs:
        buildScript[lib] = BuildScripts(os.path.join(config.THIRD_LIB_ROOT, lib))
    # print(buildScript)

    noRiskDict, riskBuildDict = WriteOkLibInfo(wb, okLibs, riskLibs, buildScript)
    print('riskBuildDict', riskBuildDict)
    projectOverview = {"ProjectName": root_name, "NORiskLib" : noRiskDict, "RiskLib" : riskBuildDict}
    WriteOverview(wb, projectOverview)
    wb.save(excelFile)

    print('共风险扫描 {0} 库, {1} 个库通过, 占比 {2}%,'.format(len(sub_libs), len(okLibs), round(len(okLibs) * 100/len(sub_libs), 3)))
    print('共风险扫描 {0} 库, {1} 个库未通过, 占比 {2}%,'.format(len(sub_libs), len(riskLibs), round(len(riskLibs) * 100/len(sub_libs), 3)))
